package com.leyou.auth.service.impl;

import com.leyou.auth.constants.JwtConstants;
import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.service.UserAuthService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.utils.CookieUtils;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.UserDTO;
import feign.FeignException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Service
public class UserAuthServiceImpl implements UserAuthService {

    @Autowired
    private UserClient userClient;

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public void login(String username, String password, HttpServletResponse response) {

        UserDTO userDTO = null;
        try {
            userDTO = this.userClient.queryUserByUsernameAndPassword(username, password);
        } catch (FeignException e) {
           throw new LyException(e.status(),e.getMessage());
        }

        UserDetail userDetail = BeanHelper.copyProperties(userDTO, UserDetail.class);

        //token生成
        String token = jwtUtils.createJwt(userDetail);


        //创建cookie，名称固定，值为token
        Cookie cookie = new Cookie(JwtConstants.COOKIE_NAME,token);

        //设置cookie绑定的域名
        cookie.setDomain(JwtConstants.DOMAIN);

        //绑定给当前域名下的路径
        cookie.setPath("/");

        //拒绝脚本操作和访问
        cookie.setHttpOnly(true);

        response.addCookie(cookie);

    }

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response) {

        //获取cookie信息然后从redis删除

        try {
            String token = CookieUtils.getCookieValue(request, JwtConstants.COOKIE_NAME);
            Payload payload = jwtUtils.parseJwt(token);
            String username = payload.getUserDetail().getUsername();

            String key = JwtConstants.KEY_PREFIX+username;

            redisTemplate.delete(key);
        } catch (Exception e) {
        }


        //创建cookie，名称固定，值为token
        Cookie cookie = new Cookie(JwtConstants.COOKIE_NAME,"");

        //设置cookie绑定的域名
        cookie.setDomain(JwtConstants.DOMAIN);

        //立即删除
        cookie.setMaxAge(0);

        //绑定给当前域名下的路径
        cookie.setPath("/");

        //拒绝脚本操作和访问
        cookie.setHttpOnly(true);

        response.addCookie(cookie);
    }
}
